using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Search.PageAdapters.Utilities;

namespace Search.PageAdapters
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("b6e033da-149d-4131-80b2-ac1b09d02c32")]
    public class PageLayoutFixupForV4EventReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = null;
            // The following if/else allows the feature scope to be changed without any significant refactoring required.
            if (properties.Feature.Parent is SPSite)
            {
                site = properties.Feature.Parent as SPSite;                
            }
            else if (properties.Feature.Parent is SPWeb)
            {
                SPWeb _web = properties.Feature.Parent as SPWeb;
                if (_web != null)
                {
                    site = _web.Site; ;
                }
            }

            try
            {
                if (site != null)
                {
                    SearchAdapters.ApplyV4SearchFixToEnterpriseSearchCenter(site, true);
                }
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("There was an error while activating the feature {0}", properties.Feature.ToString()), e);
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = null;
            // The following if/else allows the feature scope to be changed without any significant refactoring required.
            if (properties.Feature.Parent is SPSite)
            {
                site = properties.Feature.Parent as SPSite;
            }
            else if (properties.Feature.Parent is SPWeb)
            {
                SPWeb _web = properties.Feature.Parent as SPWeb;
                if (_web != null)
                {
                    site = _web.Site; ;
                }
            }

            try
            {
                if (site != null)
                {
                    SearchAdapters.ApplyV4SearchFixToEnterpriseSearchCenter(site, false);
                }
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("There was an error while deactivating the feature {0}", properties.Feature.ToString()), e);
            }
        }
    }    
}